<template>
	<div class="update-task padding">
		<el-form ref="updateTaskFormRef" class="label-inner" :model="updateTaskForm" :rules="updateTaskFormRules"
			label-position="left" label-width="120px">
			<el-row>
				<el-col>
					<el-form-item label="任务标题" prop="title">
						<el-input v-model="updateTaskForm.title" />
					</el-form-item>
					<el-form-item label="任务类型" prop="type">
						<el-select v-model="updateTaskForm.type" :placeholder="' '">
							<el-option v-for="(name, value) in taskTypeOptions" :key="value" :label="name"
								:value="value" />
						</el-select>
					</el-form-item>
					<el-form-item label="指定完成日期" prop="finishDate">
						<el-date-picker v-model="updateTaskForm.finishDate" prefix-icon="el-icon" type="datetime"
							:editable="false" :clearable="false" />
					</el-form-item>
					<el-form-item label="任务内容" prop="content" style="flex-direction: column">
						<el-input v-model="updateTaskForm.content" class="el-textarea" type="textarea" />
					</el-form-item>
					<el-form-item label="执行人" prop="handleUserName">
						<van-field v-model="handleUserNameField" is-link readonly
							@click="showPopupOfHandleUserNameCascade = true" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div v-if="updateTaskForm.taskFileList.length > 0" class="form-item-appendix-list">
			<div v-for="appendixItem in updateTaskForm.taskFileList" :key="appendixItem.attachmentId"
				class="form-item-appendix-item">
				<div class="appendix-item-left">
					<span class="iconfont" :class="fileIconClass(appendixItem.filename)" />
					<span class="appendix-name" style="margin-left: 0.5rem">{{
            appendixItem.filename
          }}</span>
				</div>
				<div class="appendix-item-right">
					<span class="action-delete-appendix-wrapper">
						<van-icon class="action-delete-appendix" name="clear" @click="removeTaskFile(appendixItem)" />
					</span>
				</div>
			</div>
		</div>
		<el-upload v-loading="uploadConfig.isUploading" class="action-upload upload-border" :data="uploadConfig.data"
			:headers="uploadConfig.headers" :action="uploadConfig.url" :disabled="uploadConfig.isUploading"
			:auto-upload="true" :on-progress="() => (uploadConfig.isUploading = true)" :on-success="handleFileSuccess"
			:on-error="handleFileError" :show-file-list="false" drag>
			<div class="button-text">
				<span class="iconfont icon-bangong-shangchuan" />
				<span>上传文件</span>
			</div>
			<!--        <div class="upload-tip">-->
			<!--          可上传 doc/pdf/rar 文件，且不超过500kb-->
			<!--        </div>-->
		</el-upload>
		<el-row class="action-row" :gutter="10">
			<el-col :span="12">
				<el-button class="action-submit" size="medium" @click="initUpdateTaskForm">
					取消
				</el-button>
			</el-col>
			<el-col :span="12">
				<el-button type="primary" class="action-submit" size="medium" @click="updateTaskFormSubmit">
					提交
				</el-button>
			</el-col>
		</el-row>
		<van-popup v-model:show="showPopupOfHandleUserNameCascade" round position="bottom">
			<van-cascader v-model="updateTaskForm.handleUserId" title="请选择所在地区"
				:options="optionsOfHandleUserNameCascade" :field-names="fieldNamesOfHandleUserNameCascade"
				:closeable="false" @finish="onUserNameCascadeFinish" />
		</van-popup>
	</div>
</template>

<script>
	// import { onMounted, reactive, ref } from "vue";
	import {
		taskTypeOptions
	} from "../../constants/taskConstant";
	// import { getTask, updateTask } from "@/api/task";
	// import { Toast } from "vant";
	// import { getToken } from "@/utils/auth";
	// import { treeUser } from "@/api/user";
	// import { fileIconClass } from "@/utils/fileUtil";
	// import RouterUtilComposition from "@/composition/RouterUtilComposition";

	// ----- [ pre ] -----

	const {
		goBackToParent
	} = RouterUtilComposition();
	const props = defineProps({
		taskId: {
			type: String,
			default: undefined,
		},
	});
	const {
		taskId
	} = props;
	if (!props.taskId) {
		goBackToParent();
	}

	// ----- [ data ] -----

	const updateTaskFormRef = ref(null);
	const updateTaskForm = reactive({
		id: taskId,
		title: "",
		type: "",
		handleUserId: null,
		handleUserName: "",
		finishDate: null,
		content: "",
		taskFileList: [],
	});
	const updateTaskFormRules = reactive({
		title: [{
			required: true,
			message: "请输入标题",
			trigger: "blur",
		}, ],
		type: [{
			required: true,
			message: "请选择类型",
			trigger: "blur",
		}, ],
		handleUserName: [{
			required: true,
			message: "请选择执行人",
			trigger: "blur",
		}, ],
		finishDate: [{
			required: true,
			message: "请选择完成日期",
			trigger: "blur",
		}, ],
		content: [{
			required: true,
			message: "请输入任务内容",
			trigger: "blur",
		}, ],
	});

	const handleUserNameField = ref("");
	const showPopupOfHandleUserNameCascade = ref(false);
	const optionsOfHandleUserNameCascade = ref([]);
	const fieldNamesOfHandleUserNameCascade = {
		text: "label",
		value: "id",
		children: "children",
	};

	const uploadConfig = reactive({
		// 是否禁用上传
		isUploading: false,
		// 设置上传的请求头部
		headers: {
			Authorization: "Bearer " + getToken()
		},
		data: {
			module: "cmdb.resource",
			dataid: "resource",
			single: false,
			filetypes: "",
		},
		// 上传的地址
		url: process.env.VUE_APP_BASE_API + "/system/attachment/attachment/upload",
	});

	// ----- [ method ] -----

	function getHandleUserNameField(options, id) {
		for (let i = 0, len = options.length; i < len; i++) {
			const option = options[i];
			const children = option["children"];
			if (children) {
				const tempField = getHandleUserNameField(children, id);
				if (tempField) {
					return option["label"] + "/" + tempField;
				}
			} else {
				if (id === option.id) {
					return option["label"];
				}
			}
		}
		return "";
	}

	function initUpdateTaskForm() {
		updateTaskForm.title = "";
		updateTaskForm.type = "";
		updateTaskForm.finishDate = null;
		updateTaskForm.content = "";
		updateTaskForm.taskFileList.splice(0);
		updateTaskForm.handleUserId = null;
		updateTaskForm.handleUserName = "";
		handleUserNameField.value = "";
		treeUser().then((res) => {
			let optionsOfHandleUserNameCascadeValue;
			if (!res.data || res.data.length < 1) {
				optionsOfHandleUserNameCascadeValue = [];
			} else {
				optionsOfHandleUserNameCascadeValue = res.data[0].children;
			}
			optionsOfHandleUserNameCascade.value = optionsOfHandleUserNameCascadeValue;
			getTask(taskId).then((res) => {
				if (!res.data) {
					Toast("获取不到数据");
					return;
				}
				console.log(res.data);
				const {
					title,
					type,
					handleUserId,
					finishDate,
					content,
					taskFileList
				} =
				res.data;
				updateTaskForm.title = title;
				updateTaskForm.type = type;
				updateTaskForm.handleUserId = handleUserId;
				updateTaskForm.finishDate = finishDate;
				updateTaskForm.content = content;
				updateTaskForm.taskFileList.push(...taskFileList);
				handleUserNameField.value = getHandleUserNameField(
					optionsOfHandleUserNameCascadeValue,
					handleUserId
				);
				updateTaskForm.handleUserName =
					handleUserNameField.value.split("/").reverse()[0] || "";
			});
		});
	}

	function updateTaskFormSubmit() {
		updateTaskFormRef.value.validate((valid) => {
			if (valid) {
				updateTask(updateTaskForm)
					.then(() => {
						Toast("提交成功");
						initUpdateTaskForm();
					})
					.catch((err) => {
						console.log(err);
						Toast("提交失败");
					});
			}
		});
	}

	function onUserNameCascadeFinish({
		selectedOptions
	}) {
		showPopupOfHandleUserNameCascade.value = false;
		const temp_options = selectedOptions.map((option) => option.label);
		if (temp_options.length > 0) {
			handleUserNameField.value = temp_options.join("/");
			updateTaskForm.handleUserName = temp_options[temp_options.length - 1];
		} else {
			handleUserNameField.value = "";
			updateTaskForm.handleUserName = "";
		}
	}

	// ----- [ uploader & appendix method ] -----

	function handleFileSuccess(response, file, fileList) {
		uploadConfig.isUploading = false;
		const {
			code,
			data
		} = response;
		if (code === 200) {
			updateTaskForm.taskFileList.push({
				attachmentId: data.id,
				filename: data.name,
			});
		} else {
			Toast("文件上传失败");
		}
	}

	function handleFileError() {
		uploadConfig.isUploading = false;
		Toast("文件上传失败");
	}

	function removeTaskFile(target) {
		updateTaskForm.taskFileList = updateTaskForm.taskFileList.filter(
			(taskFile) => taskFile !== target
		);
	}

	// ----- [ lifecycle ] -----

	onMounted(() => {
		initUpdateTaskForm();
	});
</script>

<style lang="scss">
	.update-task {
		font-size: 0.85rem;

		background-color: #ffffff;

		.el-date-editor {
			.el-input__prefix {
				display: none;
			}

			.el-input__inner {
				padding: 0 15px;
			}
		}

		.el-input {
			width: 100%;
		}

		.action-upload {
			margin-bottom: 1rem;
		}

		.action-row {
			margin-bottom: 1rem;
		}
	}
</style>